import java.util.Objects;

/**
 * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
 *
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 *
 * 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 *
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode left = l1;
        ListNode right = l2;

        int sum = 0, carry = 0;
        int type = 2;

        while (true) {
            switch (type) {
                case 0: {
                    if (carry==1) {
                        left.next = new ListNode(carry);
                    }
                    return l1;
                }
                case 1: {
                    //单线
                    while (carry == 1) {
                        if (Objects.isNull(left.next)) {
                            left.next = new ListNode(carry);
                            return l1;
                        } else {
                            left = left.next;
                            sum = left.val + carry;
                            if (sum >= 10) {
                                carry = 1;
                                sum = sum % 10;
                            } else {
                                carry = 0;
                            }
                            left.val = sum;
                        }
                    }
                    return l1;
                }
                default: {
                    sum = left.val + right.val + carry;
                    if (sum >= 10) {
                        carry = 1;
                        sum = sum % 10;
                    } else {
                        carry = 0;
                    }

                    left.val = sum;
                    right.val = sum;
                }
            }

            if (Objects.isNull(left.next)) {
                if (Objects.isNull(right.next)) {
                    type = 0;
                } else {
                    type = 1;
                    left = right;
                    l1 = l2;
                }
            } else {
                if (Objects.isNull(right.next)) {
                    type = 1;
                } else {
                    type = 2;
                    left = left.next;
                    right = right.next;
                }
            }

        }

    }
}